import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface LoginAccountInfo {
  id: number;
  nickname: string;
  avatar: string;
}

// 初始状态
const initialState: LoginAccountInfo = {
  avatar: '',
  id: NaN,
  nickname: '',
};

const LoginAccountInfoReducer = createSlice({
  name: 'loginAccountInfo',
  initialState,
  reducers: {
    // 登录成功设置账号信息
    setLoginAccountInfo: (state, action: PayloadAction<LoginAccountInfo>) => {
      console.log(`setLoginAccountInfo: ${JSON.stringify(action.payload)}`);
      state.id = action.payload.id;
      state.nickname = action.payload.nickname;
      state.avatar = action.payload.avatar;
    },

    // 更新用户信息
    updateLoginAccountInfo: (
      state,
      action: PayloadAction<LoginAccountInfo>,
    ) => {
      if (action.payload.id) state.id = action.payload.id;
      if (action.payload.avatar) state.avatar = action.payload.avatar;
      if (action.payload.nickname) state.nickname = action.payload.nickname;
    },

    // 清除账号信息（登出）
    clearLoginAccountInfo: (state) => {
      state.avatar = '';
      state.nickname = '';
      state.id = NaN;
    },
  },
});

// 导出 actions
export const {
  setLoginAccountInfo,
  updateLoginAccountInfo,
  clearLoginAccountInfo,
} = LoginAccountInfoReducer.actions;

// 导出 selector 函数
export const selectLoginAccountInfo = (state: {
  LoginAccountInfoReducer: LoginAccountInfo;
}) => {
  return state.LoginAccountInfoReducer;
};

export default LoginAccountInfoReducer.reducer;
